import { dateFormat } from '@/util';
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Cron, CronExpression } from '@nestjs/schedule';
import { PrismaClient } from '@prisma/client';
import nodemailer from 'nodemailer';
@Injectable()
export class TasksService {
  private readonly prisma = new PrismaClient();
  @Cron(CronExpression.EVERY_DAY_AT_9AM)
  async findEmailTask() {
    const prisma = new PrismaClient();
    const result = await prisma.postOffice.findMany({
      where: {
        sendDate: new Date(dateFormat(new Date())),
        status: 'READYTOSEND',
      },
    });
    // this.sednMail('qingbo789@aliyun.com', 'e.content');
    result.forEach((e, i) => {
      setTimeout(() => {
        this.sednMailTask(e.emailAddress, e.name, e.content, e.id);
      }, 1000 * 60 * i); //
    });
  }
  async sednMailTask(
    addressee: string,
    name: string,
    content: string,
    id: number,
  ) {
    const sendAddress = '42873016@qq.com';
    //引入模块 nodemailer
    // 创建一个SMTP客户端配置
    const config = {
      service: 'QQ',
      auth: {
        // 发件人邮箱账号
        user: sendAddress,
        //发件人邮箱的授权码 这里可以通过qq邮箱获取 并且不唯一
        pass: 'syvakvmcsthmbief',
      },
    };
    const transporter = nodemailer.createTransport(config);
    const mail = {
      // 发件人 邮箱  '昵称<发件人邮箱>'
      from: `时光邮局<42873016@qq.com>'`,
      // 主题
      subject: `${name}！！！时光邮局这有一封你的信`,
      // 收件人 的邮箱 可以是其他邮箱 不一定是qq邮箱
      to: addressee,
      //这里可以添加html标签
      html: `<div>${content}</div>`,
    };
    let result = '';
    try {
      result = await transporter.sendMail(mail);
      await this.prisma.postOffice.update({
        where: {
          id,
        },
        data: {
          status: 'FINISH',
        },
      });
    } catch (e) {
      console.log('error', e);
    }
    return result;
  }
}
